define(function () {
    'use strict';

    function ctrl($scope,$state,$timeout,$stateParams,WebService,CommonService,InfoService) {

        var par = $scope.param = new Array();

        var first_short = {}; //第一条短债记录
        var trade_orders = {}; //当日交易记录

        //回退固定为持仓页
        $scope.onBackKeyDown = function(){
            $state.go("tab.account-shares");
        };

        $scope.$on('$ionicView.beforeEnter', function() {
            $scope.short_term_fund = new Array(); //短债产品
            $scope.holdFund = {};   //持仓信息
            $scope.prodInfo = {};   //产品信息

            par.prevDate = CommonService.getPrevDate();
            par.allotNo = $stateParams['allotNo'];
            par.prodCode = $stateParams['prodCode'];
            par.prodSource = $stateParams['prodSource'];
            par.payAccount = $stateParams['payAccount'];
            par.pay_account_empty = CommonService.isStrEmpty(par.payAccount);
            par.enable_amount = $stateParams['enable_amount'];  //可卖出份额
            par.enableSell = false;     //是否可卖

            init();
        });

        $scope.doRefresh = function() {
            init();
            $scope.$broadcast('scroll.refreshComplete');
        };

        function init (){
            //查询份额信息
            WebService.getShares(par.prodSource,par.allotNo,par.prodCode).then(
                function (data) {
                    if(data && data.length == 1) {
                        $scope.holdFund = data[0];
                        if(par.prodSource=="2"){
                            $scope.holdFund.total_income = $scope.holdFund.income_balance;
                        }
                        //查询产品信息
                        queryProdInfo();
                    }else {
                        CommonService.showAlert({message:"持仓信息查询失败",onUnblock:function (){
                            $timeout(function(){
                                $scope.onBackKeyDown();
                            },3000);
                        }});
                    }
                }
            );
        }

        function queryProdInfo(){
            InfoService.getFundGeneral(par.prodCode).then(
                function(data){
                    if(data){
                        $scope.prodInfo = data;
                        //短债持仓26记录查询
                        InfoService.getShortTermFund(par.prodCode,$scope.holdFund.trans_account).then(
                            function(short_term){
                                if(short_term && short_term.length > 0){
                                    first_short = short_term[0];
                                    for(var i=0;i<short_term.length;i++){
                                        $scope.short_term_fund.push(short_term[i])
                                    }
                                    //可卖份额及交易状态处理
                                    showAvailableVol();
                                }else{
                                    par.enableSell = $scope.holdFund.enable_amount > 0;
                                }
                            }
                        );
                        productPageUrl();
                    }
                }
            );
        }

        function productPageUrl() {
            $scope.prodInfo.url = CommonService.productPageUrl($scope.prodInfo.prod_profit_mode, $scope.prodInfo.prod_source);
            if ($scope.prodInfo.url == null || typeof($scope.prodInfo.url) == "undefined"){
                CommonService.showConfig({message: "产品收益模式未配置:" + $scope.prodInfo.prod_code});
            }
        }

        function showAvailableVol(){
            WebService.getOrders(par.prodSource,par.prodCode,$scope.holdFund.trans_account).then(
                function (data){
                    par.enable_amount = parseFloat(first_short.availablevol);
                    if(data && data.length > 0){
                        trade_orders = data;
                        if(par.prodSource=="1"){
                            for (var i = 0; i < trade_orders.length; i++) {
                                var record = trade_orders[i];
                                par.enable_amount = par.enable_amount - parseFloat(record.entrust_amount);
                            }
                        }
                        if(par.prodSource=="2"){
                            for (var i = 0; i < trade_orders.length; i++) {
                                var record = trade_orders[i];
                                par.enable_amount = par.enable_amount - parseFloat(record.shares);
                            }
                        }
                    }
                    par.enableSell = first_short.is_redeem_date == "1" && first_short.sell_time >= "09"
                        && first_short.sell_time < "15" && par.enable_amount > 0;
                }
            );
        }

        $scope.shortDetail = function(){
            var html = "<div>卖出开放日提醒（逾期未卖出份额将自动滚存新一期）<ol>";
            for(var i=0; i<$scope.short_term_fund.length; i++){
                var short_fund = $scope.short_term_fund[i];
                var enable_amount = parseFloat(short_fund.availablevol);
                if(i==0 && trade_orders && trade_orders.length > 0){
                    if(par.prodSource=="1"){
                        for (var j = 0; j < trade_orders.length; j++) {
                            var record = trade_orders[j];
                            enable_amount = enable_amount - parseFloat(record.entrust_amount);
                        }
                    }
                    if(par.prodSource=="2"){
                        for (var j = 0; j < trade_orders.length; j++) {
                            var record = trade_orders[j];
                            enable_amount = enable_amount - parseFloat(record.shares);
                        }
                    }
                }
                var sell_time = CommonService.isStrEmpty(par.payAccount) ? " 9:00-15:00，可卖出" : " 当日15:00前，可卖出";
                html += "<li>"+ short_fund.redeem_end_date + sell_time + enable_amount +"份</li>";
            }
            html += "</ol></div>";
            CommonService.showConfig({okText: '关闭',message : html});
        }
    }

    ctrl.$inject = ['$scope','$state','$timeout','$stateParams','WebService','CommonService','InfoService'];
    return ctrl;
});
